/**
 *  学习目标：Todos 案例
 */
import React from 'react'
import './style/index.css'
import './style/base.css'

export default class App extends React.Component {
  state = {
    list: [
      // { id: 1, content: '吃饭', done: true },
      // { id: 2, content: '睡觉', done: false },
      // { id: 3, content: '游戏', done: false },
      // { id: 4, content: '代码', done: true },
      // { id: 5, content: '抖音', done: true },
      // { id: 6, content: '视频', done: true },
    ],
    type: 'all',
  }
  // 删除列表
  detDyabyIdHandle = (id) => {
    // console.log('接收到的', id)
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    })
  }
  // 更新选择状态
  changeByidlistHandle = (id) => {
    // console.log('列表id', id)
    const newList = this.state.list.map((item) => {
      if (item.id === id) {
        return {
          ...item,
          done: !item.done,
        }
      } else {
        return item
      }
    })
    this.setState({ list: newList })
  }
  // 清理完成的状态
  clearHandle = () => {
    this.setState({
      list: this.state.list.filter((item) => !item.done),
    })
  }
  // 更新状态
  typechangeHandle = (type) => {
    this.setState({ type })
    // console.log('更新的状态')
  }
  //增加状态
  addHandle = (content) => {
    // console.log(content, '接收到孩子传的数值')
    this.setState({ list: [{ id: Date.now(), content: content, done: false }, ...this.state.list] })
  }

  // 组件挂载时获取本地存储数据
  componentDidMount() {
    // console.log('组件componentDidMount')
    this.setState({
      list: JSON.parse(localStorage.getItem('todos')) || [],
      type: JSON.parse(localStorage.getItem('todosType')) || 'all',
    })
  }
  // 先更新render=>挂载componentDidMount=>render=>数据更新完成是componentDidUpdate
  // 当组件（prevProps, prevState）更新时，设置本地存储数据
  // 存本地存储转字符串
  componentDidUpdate() {
    // console.log('componentDidUpdate组件更新啦')
    localStorage.setItem('todos', JSON.stringify(this.state.list))
    localStorage.setItem('todosType', JSON.stringify(this.state.type))
  }
  // 实现全选和不全选
  checkAllHandle = (checked) => {
    console.log(checked, '父组件接收到数据')
    this.setState({
      list: this.state.list.map((item) => ({ ...item, done: checked })),
    })
  }
  render() {
    return (
      <section className='todoapp'>
        {/* 头部 */}
        <Header addHandle={this.addHandle}></Header>
        {/* 主体 */}
        <Content checkAllHandle={this.checkAllHandle} list={this.state.list} type={this.state.type} detDyabyIdHandle={this.detDyabyIdHandle} changeByidlistHandle={this.changeByidlistHandle}></Content>
        {/* 底部 */}
        <Footer type={this.state.type} typechangeHandle={this.typechangeHandle} list={this.state.list} clearHandle={this.clearHandle}></Footer>
      </section>
    )
  }
}
class Header extends React.Component {
  state = {
    content: '',
  }
  // react一定要写这个onchange事件表单才会显示输入
  changeHandle = (e) => {
    // console.log(e.target.value)
    const content = e.target.value.trim()
    this.setState({ content })
  }
  // onkeyUp鼠标按下事件
  keyupHandle = (e) => {
    // console.log(e)
    // key的按下键 __Enter
    // keycode的键盘编码
    if (e.key === 'Enter') {
      if (e.target.value === '') return
      this.props.addHandle(this.state.content)
      this.setState({ content: '' })
      // key的esc键 Escape
    } else if (e.key === 'Escape') {
      this.setState({ content: '' })
    }
  }
  render() {
    return (
      <header className='header'>
        <h1>todos</h1>
        <input onKeyUp={this.keyupHandle} value={this.state.content} onChange={this.changeHandle} className='new-todo' placeholder='What needs to be done?' autoFocus />
      </header>
    )
  }
}

class Content extends React.Component {
  render() {
    const { list, detDyabyIdHandle, changeByidlistHandle, type } = this.props
    let typeList = []
    if (type === 'all') {
      typeList = list
    } else if (type === 'active') {
      typeList = list.filter((v) => !v.done)
    } else if (type === 'completed') {
      typeList = list.filter((v) => v.done)
    }
    // .every() 测试一个数组内的所有元素是否都能通过某个指定函数的测试
    const checkAll = list.length !== 0 && list.every((item) => item.done)
    return (
      <section className='main'>
        <input className='toggle-all' onChange={(e) => this.props.checkAllHandle(e.target.checked)} checked={checkAll} type='checkbox' id='toggle-all' />
        <label htmlFor='toggle-all'>Mark all as complete</label>
        <ul className='todo-list'>
          {typeList.map((item) => (
            <li key={item.id} className={item.done ? 'completed' : ''}>
              <div className='view'>
                <input className='toggle' checked={item.done} onChange={() => changeByidlistHandle(item.id)} type='checkbox' />
                <label>{item.content}</label>
                <button className='destroy' onClick={() => detDyabyIdHandle(item.id)}></button>
              </div>
              <input className='edit' />
            </li>
          ))}
        </ul>
      </section>
    )
  }
}

class Footer extends React.Component {
  state = {
    leftNum: 0,
  }
  render() {
    const { list, clearHandle, typechangeHandle, type } = this.props
    return (
      <footer className='footer' style={{ display: list.length === 0 ? 'none' : '' }}>
        <span className='todo-count'>
          {/* 更新剩下的事项 */}
          <strong>{list.filter((v) => !v.done).length}</strong> item left
        </span>
        <ul className='filters'>
          <li onClick={() => typechangeHandle('all')}>
            <a className={type === 'all' ? 'selected' : ''} href='#/'>
              All
            </a>
          </li>
          <li onClick={() => typechangeHandle('active')}>
            <a className={type === 'active' ? 'selected' : ''} href='#/active'>
              Active
            </a>
          </li>
          <li onClick={() => typechangeHandle('completed')}>
            <a className={type === 'completed' ? 'selected' : ''} href='#/completed'>
              Completed
            </a>
          </li>
        </ul>
        <button className='clear-completed' onClick={clearHandle}>
          Clear completed
        </button>
      </footer>
    )
  }
}
